package kassiopeia.agent.seda.threads;

import kassiopeia.agent.internal.Constants;
import org.apache.log4j.Logger;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class StagePool {

    private Logger logger = Logger.getLogger(StagePool.class);
    private ThreadPoolExecutor threadPoolExecutor;

    public StagePool() {
        this.threadPoolExecutor = new ThreadPoolExecutor(
                Constants.DEFAULT_STAGE_POOL_SIZE,
                Constants.DEFAULT_STAGE_POOL_SIZE,
                1, TimeUnit.DAYS,
                new LinkedBlockingQueue<Runnable>());
    }

    public void execute(Runnable process) {
        this.threadPoolExecutor.execute(process);
    }

    public void shutdown() {
        this.threadPoolExecutor.shutdown();
        while (threadPoolExecutor.isTerminating()) {
            try {
                TimeUnit.SECONDS.sleep(1L);
            } catch (InterruptedException ex) {
                logger.error(ex, ex);
            }
        }
    }

    public void shutdownNow() {
        this.threadPoolExecutor.shutdownNow();
    }

    public boolean isTerminating() {
        return this.threadPoolExecutor.isTerminating();
    }

    public void setSize(int size) {
        threadPoolExecutor.setCorePoolSize(size);
        threadPoolExecutor.setMaximumPoolSize(size);
    }

    public int size() {
        return this.threadPoolExecutor.getCorePoolSize();
    }

    public int waitingForExecution() {
        return this.threadPoolExecutor.getQueue().size();
    }

    public int activeCount() {
        return this.threadPoolExecutor.getActiveCount();
    }
    
    public int getPoolSize() {
        return this.threadPoolExecutor.getPoolSize();
    }
}
